package com.dididoctor.patient.Activity.Message.SystemMessage;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;

import com.dididoctor.patient.Activity.Inquiry.InquiryActivity;
import com.dididoctor.patient.Bean.DiaeasesLitapal;
import com.dididoctor.patient.Bean.Token;
import com.dididoctor.patient.Dialog.DiseaseListDialog;
import com.dididoctor.patient.MV.BaseFragment;
import com.dididoctor.patient.R;
import com.dididoctor.patient.Ui.customlistview.OnRefreshListener;
import com.dididoctor.patient.Ui.customlistview.RefreshListView;
import com.dididoctor.patient.Utils.SharedPreferencesUtils;
import com.dididoctor.patient.WYY.Medicaladvice.MedicaladviceAttachment;
import com.dididoctor.patient.WYY.SessionHelper;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallbackWrapper;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.attachment.MsgAttachment;
import com.netease.nimlib.sdk.msg.constant.MsgTypeEnum;
import com.netease.nimlib.sdk.msg.model.RecentContact;

import java.util.ArrayList;
import java.util.List;

/**
 * @version 2.0
 * @类描述：
 * @项目名称：ddgh
 * @类名称： SystemMessageFragment
 * @包名称： com.dididoctor.patient.Activity.Message.SystemMessage
 * @创建人： zhanjunjie
 * @创建时间：2016/4/14 16:46
 * @修改人：
 * @修改时间：2016/4/14 16:46
 * @修改备注： new parent class(用一句话描述修改了什么)
 */
public class PersonalFragment extends BaseFragment implements SystemMessageView {
    private Activity activity;
    private SystemMessagePresenter presenter;
    private RefreshListView listview;
    private PersonalAdapter adapter;
    private List<PersonalBean> messages = new ArrayList<PersonalBean>();

    private int pageIndex = 1;
    private int loadOffset = 0;
    private String status;
    private List<DiaeasesLitapal> litapals = new ArrayList<>();
    private String name;
    private View rootView;

    public PersonalFragment() {
    }

    @SuppressLint("ValidFragment")
    public PersonalFragment(String status) {
        this.status = status;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    @Override
    public void onAttach(Activity activity) {
        this.activity = activity;
        super.onAttach(activity);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.activity_forum_module, null);
        this.initView(rootView);
        return rootView;

    }

    @Override
    public void onResume() {
        super.onResume();
        this.initView(rootView);
    }

    private void initView(View rootView) {
        presenter = new SystemMessagePresenter(getActivity(), this);
        listview = (RefreshListView) rootView.findViewById(R.id.lv_forum);
        adapter = new PersonalAdapter(getActivity(), messages,presenter);
        listview.setAdapter(adapter);
        listview.setHeadAndFoot(false, false);
        listview.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onPullDownRefresh() {
                getData();
            }

            @Override
            public void onLoadMoring() {
                listview.onRefreshFinish();
            }

            @Override
            public void onScrollListener(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });



        //设置数据
        getData();


//        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                name = adapter.getItem(position - 1).getName();
//                String isSignDoctorid = SharedPreferencesUtils.getParam(getActivity(), "isSignDoctorid", "0");
//                String issign = "0";
//                if (isSignDoctorid.equals(adapter.getItem(position - 1).getDoctorId())) {
//                    issign = "1";
//                } else {
//                    issign = "0";
//                }
//                presenter.getgoAndFrom(adapter.getItem(position - 1).getHospitalId(), adapter.getItem(position - 1).getDoctorId(), adapter.getItem(position - 1).getSessionId(), issign);
//            }
//        });

        //24z中小病
        litapals = DiaeasesLitapal.getdisarases();
    }

    /**
     * 设置数据
     * @return
     */
    public void getData() {
        NIMClient.getService(MsgService.class).queryRecentContacts()
                .setCallback(new RequestCallbackWrapper<List<RecentContact>>() {
                    @Override
                    public void onResult(int code, List<RecentContact> recents, Throwable e) {
                        if (recents != null) {
                            // recents参数即为最近联系人列表（最近会话列表）
                            String ids = "";
                            List<MedicaladviceAttachment> ma = new ArrayList<MedicaladviceAttachment>();
                            List<TimeBean> time = new ArrayList<TimeBean>();
                            List<YXBean> ls = new ArrayList<YXBean>();
                            String s = "";

                            for (int x = 0; x < recents.size(); x++) {
                                YXBean yxb = new YXBean();
                                ids += recents.get(x).getContactId() + ",";
                                yxb.setAddId(recents.get(x).getContactId());
                                if (recents.get(x).getUnreadCount() > 0) {
                                    yxb.setStatus("0");
                                } else {
                                    yxb.setStatus("1");
                                }
                                if (recents.get(x).getMsgType() == MsgTypeEnum.custom) {
                                    yxb.setMsgType(recents.get(x).getMsgType());
                                    MsgAttachment attachment = recents.get(x).getAttachment();
                                    if (attachment != null) {
                                        s = attachment.toJson(false);
                                        yxb.setData(s);
                                    }
                                } else if (recents.get(x).getMsgType() == MsgTypeEnum.tip) {
                                    yxb.setMsgType(recents.get(x).getMsgType());
                                    String content = "结束会话";
                                    yxb.setData(content);
                                } else if (recents.get(x).getMsgType() == MsgTypeEnum.text) {
                                    yxb.setMsgType(recents.get(x).getMsgType());
                                    String content = recents.get(x).getContent();
                                    yxb.setData(content);
                                } else if (recents.get(x).getMsgType() == MsgTypeEnum.image) {
                                    yxb.setMsgType(recents.get(x).getMsgType());
                                    String content = recents.get(x).getContent();
                                    yxb.setData(content);
                                } else if (recents.get(x).getMsgType() == MsgTypeEnum.audio) {
                                    yxb.setMsgType(recents.get(x).getMsgType());
                                    String content = recents.get(x).getContent();
                                    yxb.setData(content);
                                }

////                            JSONObject jsStr = JSONObject.fromObject(params);
//                              ma.add(attachment);
                                TimeBean timeBean = new TimeBean();
                                timeBean.setTime(recents.get(x).getTime() + "");
                                time.add(timeBean);
                                ls.add(yxb);
                            }
                            if (!"".equals(ids) && ids != null) {
                                ids = ids.substring(0, ids.length() - 1);
                                presenter.getfindDoctorByIds(ids, ls, time);
                            }else{
                                listview.onRefreshFinish();
                            }
                        }

                    }
                });
    }


    @Override
    public void getmessage(List<SystemMessage> messages) {
    }

    @Override
    public void getPersonalmessage(List<PersonalBean> messages) {
        adapter.setData(messages);
        listview.onRefreshFinish();
        adapter.notifyDataSetChanged();
    }

    @Override
    public void getmessagefail() {
        showToastMessage("网络连接失败，请检查您的网络设置");
        listview.onRefreshFinish();
    }

    @Override
    public void IntentInquiryActivity(final String isCmp, final String hosId, final String doctorID, final String accID) {
        DiseaseListDialog diseaseListDialog = new DiseaseListDialog(getActivity(), litapals, new DiseaseListDialog.onItemClickListener() {
            @Override
            public void itemClick(int position) {
                DiaeasesLitapal litapal = litapals.get(position);
                String disname = litapal.getName();
                String disid = litapal.getDisId();
                Intent intent = new Intent(getActivity(), InquiryActivity.class);
                intent.putExtra("disname", disname);
                intent.putExtra("disid", disid);
                intent.putExtra("doctorId", doctorID);
                intent.putExtra("hosId", hosId);
                intent.putExtra("isCmp", isCmp);
                intent.putExtra("accId", accID);
                intent.putExtra("sign", "1");
                intent.putExtra("name", name);
                startActivity(intent);
            }

            @Override
            public void setfinis() {

            }
        });
        diseaseListDialog.show();
    }

    @Override
    public void IntentP2PActivity(String recId, String status, String hosId, String doctorID, String accId, String isSign,String name) {
        this.name = name;
        //Todo hosId医生医院id和recId问诊表id   //doctorid医院的ID    accId聊天人的云信ID
        SessionHelper.startP2PSession(getActivity(), accId, status, recId, hosId, Token.getId(), Token.getToken(), doctorID, accId,  this.name, isSign);
    }

    @Override
    public void IntentP2PActivityGo() {

    }

    @Override
    public void IntentP2PActivityTwo() {

    }

    @Override
    public void getdoctorfail() {
        showToastMessage("网络连接失败，请检查您的网络设置");
        listview.onRefreshFinish();
    }


}
